//
//  HJCStatusDAL.swift
//  新浪微博Swift
//
//  Created by 郝俊聪 on 15/5/27.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit
import SVProgressHUD

private let FRIDENDS_TIMELINE_URL = "https://api.weibo.com/2/statuses/friends_timeline.json"

class HJCStatusDAL: NSObject {
    
    class func loadStatuses(since_id:Int,max_id:Int,finished:(array : [[String:AnyObject]]?)->()){
        
        checkingDB(since_id, max_id: max_id, finished: finished)
    
    }
    
    
    ///判断有没有本地数据
    class func checkingDB(since_id:Int,max_id:Int,finished:(array : [[String:AnyObject]]?)->()){
        //先写好sql
        var sql = "SELECT status FROM T_Status WHERE userID == \(sharedaccount!.uid) \n"
        if since_id > 0{
           sql += "AND statusID > \n"+"\(since_id)\n"
        }else if max_id > 0{
            sql += "AND statusID < \n"+"\(max_id)\n"
        }
        sql += "ORDER BY statusID DESC LIMIT 20;\n"  //最多取20条
        
        //执行sql
        let array = SQLiteManager.sharedSQLManager().execRecordSet(sql)
        
        if array == nil || array?.count == 0{
            //没有数据，网络加载
            downloadStatuses(since_id, max_id: max_id,finished:finished)
        }else{
           //用数据，从本地读取
           //创建一个可变数组，接收statua字典
            var arrayM = [[String:AnyObject]]()
           //遍历装换
            for dict in array!{
                //将数据转成二进制
                let str = dict["status"] as! NSString
                let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
                //反序列化成json
                let json = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(0), error: nil) as! [String:AnyObject]
                //添加到数组中
                arrayM.append(json)
            }
            //回调
            finished(array: arrayM)
        }
    }
    
    
    
    
    ///假如没有从网络加载
    class func downloadStatuses(since_id:Int,max_id:Int,finished:(array : [[String:AnyObject]]?)->()){
        let urlStr = FRIDENDS_TIMELINE_URL
        var param = ["access_token":sharedaccount!.access_token] as [String:AnyObject?]
        if since_id > 0{
            param["since_id"] = since_id
        }
        if max_id > 0{
            param["max_id"] = max_id - 1
        }
        //从网络加载首页微博数据
        HJCNetWorkTools.requestJSON(.GET, URLString: urlStr, parameters: param as? [String : AnyObject]) { (JSON) -> () in
            
            //处理数据
            if JSON == nil{
                SVProgressHUD.showErrorWithStatus("获取数据错误")
                finished(array: nil)
                return
            }
            
            //处理数据
            //预处理一下JSON
            let array = (JSON as! [String : AnyObject])["statuses"] as? [[String : AnyObject]]
            

            if array == nil{
                finished(array: nil)
                return
            }
            //回调
            finished(array: array)
            //如果有数据，保存到本地
            self.saveStatusToDB(array!)
        }
        
    }
    
    ///保存到本地
    class func saveStatusToDB(array:[[String : AnyObject]]){
        let manager = SQLiteManager.sharedSQLManager()
        manager.beginTransction()  //开始事务
        var result = true
            //1.遍历数组,批量写入
        for dict in array{
            //将数据二进制化
            let data = NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions(0), error: nil)
            //再转成字符串
            let str = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
//            println(str)
            //取得微博ID
            let statusID = dict["id"] as! Int
//            println(statusID)
            //当前操作人的id
            let userID = sharedaccount!.uid
//            println(userID)
            //写出sql
            let sql = "INSERT OR REPLACE INTO T_Status (statusID,status,userID) VALUES (?,?,?);"
            //写入
            result = manager.execUpdate(sql, params: statusID,str,userID)
            //假如写入失败，跳出循环
            if result == false{
                break
            }
        }
        if result == true{
            //成功则提交事务
            manager.commitTransction()
        }else{
            //失败就回滚
            manager.rollbackTransction()
        }
    }
    
    ///自动清理数据库缓存数据，暂定清理7天之前的
    class func autoClearDBDate(){
        //获取7天之前的日期
        let date = NSDate(timeIntervalSinceNow: -60*60*24*7)
        //转成与数据库格式一致的字符串
        let df = NSDateFormatter()
        df.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateStr = df.stringFromDate(date)
        println(dateStr)
        //删除数据的sql
        let deleteSql = "DELETE FROM T_Status WHERE creatDate < '\(dateStr)';"
        
        //执行sql
        SQLiteManager.sharedSQLManager().execSQL(deleteSql)
    
    }
    
   
}
